import { Service } from 'egg';

/**
 * Categories Service
 */
const categoryColumns = [ 'id', 'alias' ];
const categoryStatisticsColumns = [ 'category_id', 'category_alias', 'article_total' ];
export default class Categories extends Service {
  mysql = this.app.mysql as any;
  /**
   * 获取分类，不传入参数时，返回所有ID
   * ? @param id - 可选，categories.ID
   * ? @param alias - 可选，categories.alias
   * ? @param hasStatistics - 可选, 默认为false，不返回统计的文章数
   */
  public async get(id?:number, alias?: string, hasStatistics = false) {
    // 构造where
    const where:{
      id?:number,
      alias?:string
    } = {};
    if (id) where.id = id;
    if (alias) where.alias = alias;
    // 判断如果需要统计需要统计
    if (hasStatistics) {
      const categoryStatistics:{ category_id:number, category_alias: string, article_total: number}[] = await this.mysql.select('category_statistics', {
        columns: categoryStatisticsColumns,
        where,
      });
      return categoryStatistics;
    }
    // 如果不需要统计
    const categories:{ id:number, alias: string}[] = await this.mysql.select('categories', {
      columns: categoryColumns,
      where,
    });
    // 重新格式化类别信息
    const formatCategories = categories.map(item => {
      return {
        category_id: item.id,
        category_alias: item.alias,
      };
    });
    return formatCategories;
  }

}
